package com.bluemoon.daps.test.sync.v1_3.model2dev;

import cn.com.bluemoon.daps.common.enums.SyncToEnv;
import cn.com.bluemoon.daps.common.toolkit.SshUtils;
import cn.com.bluemoon.daps.sync.DapsSyncApplication;
import cn.com.bluemoon.daps.sync.base.CompareResult;
import cn.com.bluemoon.daps.sync.base.ModifyType.ModifyLevel;
import cn.com.bluemoon.daps.sync.base.SqlCompareResult;
import cn.com.bluemoon.daps.sync.core.sync.TableModel;
import cn.com.bluemoon.daps.sync.core.sync.compare.ModelCompareClient;
import cn.com.bluemoon.daps.sync.core.sync.compare.ModelCompareClient.BizType;
import cn.com.bluemoon.daps.sync.core.sync.executor.SqlExecutor;
import cn.com.bluemoon.daps.sync.core.sync.executor.SqlExecutors;
import com.bluemoon.daps.test.sync.v1_3.devimport.BaseBefore;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.util.function.Tuple2;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Jarod.Kong
 * @date 2021/6/2 16:35
 */
@SpringBootTest(classes = DapsSyncApplication.class)
@RunWith(value = SpringRunner.class)
@Slf4j
public class Model2TestV2 extends BaseBefore {


    public Model2TestV2() {
        super(SyncToEnv.TEST);
    }

    /**
     * <pre>
     * 根据所选的表
     * in:
     *   table_ids [],
     *   model_id,
     * check:
     *  model_id & table_ids 对应
     *  table & dap_sync_dev_env_task#sync_status是否为可执行状态
     *
     * out:
     *  table_ddl_sql
     *
     * </pre>
     */
    @Test
    public void test_api_click_sync_dev() {

    }

    /**
     * 获取模型下的表数据+最新同步状态 数据
     * <pre>
     *     in:
     *      model_id,
     *      searchVo:
     *          keyword:
     *          dev_status:
     *          test_status:
     *     out:
     *      table_info:
     *      sync_info:
     *
     * </pre>
     */
    @Test
    public void test_query_dev_sync_list() {
        Tuple2<List<TableModel>, List<TableModel>> localAndMetadataTableModel = getLocalAndMetadataTableModel();
        List<TableModel> modelV1 = localAndMetadataTableModel.getT1();
        List<TableModel> modelV2 = localAndMetadataTableModel.getT2();
        globalConfig.setCheckSqlLayer(true);
        globalConfig.setCanDropDbTable(false);
        List<Map<ModifyLevel, List<CompareResult<SqlCompareResult>>>> compareR = ModelCompareClient
                .doCompare(BizType.SQL, globalConfig, modelV2, modelV1);
        log.info("模型导入开发库（开发同步）：{}, size={}", compareR, compareR.size());
        List<CompareResult<SqlCompareResult>> res = compareR.stream().flatMap(m -> m.entrySet().stream()).flatMap(e -> e.getValue().stream()).collect(Collectors.toList());
    }

    /**
     * 查看任务列表
     */
    @Test
    public void test_cat_sync_dev_and_test_log_1() {

    }

    /**
     * 查看任务列表下查看执行日志
     */
    @Test
    public void test_cat_sync_dev_and_test_log_2_view_log() {

    }


    /**
     * 开发-模型相互对比-生成sql、pt sql
     */
    @Test
    public void test_dev2model_and_mode2dev_sql_2DB() {
        Tuple2<List<TableModel>, List<TableModel>> localAndMetadataTableModel = getLocalAndMetadataTableModel();
        List<TableModel> modelV1 = localAndMetadataTableModel.getT1();
        List<TableModel> modelV2 = localAndMetadataTableModel.getT2();
        globalConfig.setCheckSqlLayer(true);
        globalConfig.setCanDropDbTable(false);
        List<Map<ModifyLevel, List<CompareResult<SqlCompareResult>>>> compareR = ModelCompareClient
                .doCompare(BizType.SQL, globalConfig, modelV2, modelV1);
        log.info("模型导入开发库（开发同步）：{}, size={}", compareR, compareR.size());
        // 根据模型对应的数据源中的开关（是否开启ptosc同步）
        Boolean isPtosc = globalConfig.getDataSource().getIsPtosc();
        SqlExecutor.ExecutorType type;
        if (isPtosc == null || Boolean.TRUE.equals(isPtosc)) {
            type = SqlExecutor.ExecutorType.PT;
        } else {
            type = SqlExecutor.ExecutorType.JDBC;
        }
        // 异步提交等待返回
        SqlExecutor sqlExecutor = SqlExecutors.use(type, globalConfig).async().sqlResult(compareR);
        boolean logInfoCollectors = sqlExecutor.execute();
        System.out.println(logInfoCollectors);
    }

    /**
     * 用户实时获取同步中的日志内容，
     * 而同步失败+已同步则无需ssh登录获取
     * 同时已同步完成则把服务器上的日志进行清除
     */
    @Test
    public void test_ssh_server_log_file() {
        SshUtils.client().session(session -> {
            try (FileOutputStream stdOut = new FileOutputStream("pt_log_1623048661345.log")) {
                String logContent = session.executeRemoteCommand("cat /home/ptadmin/pt_log_1623048661345.log", stdOut, StandardCharsets.UTF_8);
                System.out.println(logContent);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    @Test
    public void test_ssh_server_log_file_and_delete() {
        test_ssh_server_log_file();
        SshUtils.client().session(session -> {
            try {
                String s = session.executeRemoteCommand("touch /home/ptadmin/test.log; rm -f /home/ptadmin/test.log");
                System.out.println("结果：" + s); // 为空已删除
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

}
